<template>
  <ElDialog
    v-model="dialogVisible"
    title="商品品牌管理"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="brand-dialog-content">
      <!-- 工具栏 -->
      <div class="toolbar">
        <ElButton type="primary" @click="showAddDialog">
          <ElIcon><Plus /></ElIcon>
          新增品牌
        </ElButton>
        <ElButton @click="refreshData">
          <ElIcon><Refresh /></ElIcon>
          刷新
        </ElButton>
      </div>

      <!-- 品牌列表 -->
      <ElTable
        :data="brandList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <ElTableColumn type="index" label="序号" width="60" align="center" />

        <ElTableColumn prop="brandCode" label="品牌编码" width="120" />

        <ElTableColumn prop="brandName" label="品牌名称" min-width="150" />

        <ElTableColumn prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <ElTag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "启用" : "禁用" }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn
          prop="remark"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        />

        <ElTableColumn prop="createTime" label="创建时间" width="180" />

        <ElTableColumn label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <ElButton type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </ElButton>
            <ElButton
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>

    <template #footer>
      <ElButton @click="handleClose">关闭</ElButton>
    </template>

    <!-- 品牌编辑弹窗 -->
    <ElDialog
      v-model="editDialogVisible"
      :title="editType === 'add' ? '新增品牌' : '编辑品牌'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
      append-to-body
    >
      <ElForm
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <ElFormItem label="品牌编码" prop="brandCode">
          <ElInput
            v-model="formData.brandCode"
            placeholder="请输入品牌编码"
            :disabled="editType === 'edit'"
          />
        </ElFormItem>

        <ElFormItem label="品牌名称" prop="brandName">
          <ElInput v-model="formData.brandName" placeholder="请输入品牌名称" />
        </ElFormItem>

        <ElFormItem label="状态" prop="status">
          <ElRadioGroup v-model="formData.status">
            <ElRadio :label="1">启用</ElRadio>
            <ElRadio :label="0">禁用</ElRadio>
          </ElRadioGroup>
        </ElFormItem>

        <ElFormItem label="备注" prop="remark">
          <ElInput
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="editDialogVisible = false">取消</ElButton>
          <ElButton
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            确定
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useWmsStore } from "@/store/modules/wms";
import { WmsItemBrandService } from "@/api/wms/basicApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsItemBrandDialog" });

// Props
interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
});

// Emits
interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "submit"): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const wmsStore = useWmsStore();

// 弹窗状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// 品牌列表
const brandList = computed(() => {
  return wmsStore.itemBrandList || [];
});

const loading = ref(false);

// 编辑弹窗
const editDialogVisible = ref(false);
const editType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const submitLoading = ref(false);

// 表单数据
const formData = ref<Partial<WMS.Basic.ItemBrandInfo>>({
  brandCode: "",
  brandName: "",
  status: 1,
  remark: "",
});

// 表单验证规则
const formRules: FormRules = {
  brandCode: [
    { required: true, message: "请输入品牌编码", trigger: "blur" },
    { min: 2, max: 50, message: "品牌编码长度在2-50个字符", trigger: "blur" },
  ],
  brandName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 100, message: "品牌名称长度在2-100个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听弹窗显示
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      refreshData();
    }
  },
);

// 刷新数据
const refreshData = () => {
  wmsStore.getItemBrandList();
};

// 显示新增弹窗
const showAddDialog = () => {
  editType.value = "add";
  formData.value = {
    brandCode: "",
    brandName: "",
    status: 1,
    remark: "",
  };
  editDialogVisible.value = true;
};

// 编辑品牌
const handleEdit = (row: WMS.Basic.ItemBrandInfo) => {
  editType.value = "edit";
  formData.value = { ...row };
  editDialogVisible.value = true;
};

// 删除品牌
const handleDelete = async (row: WMS.Basic.ItemBrandInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除品牌"${row.brandName}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await WmsItemBrandService.deleteItemBrand(row.id);
    ElMessage.success("删除成功");
    refreshData();
    emit("submit");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    submitLoading.value = true;

    if (editType.value === "add") {
      await WmsItemBrandService.createItemBrand(
        formData.value as WMS.Basic.ItemBrandCreateParams,
      );
      ElMessage.success("新增品牌成功");
    } else {
      await WmsItemBrandService.updateItemBrand(
        formData.value.id!,
        formData.value,
      );
      ElMessage.success("更新品牌成功");
    }

    editDialogVisible.value = false;
    refreshData();
    emit("submit");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.brand-dialog-content {
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }
}
</style>
